package com.leetcode.根据算法进行分类.滑动窗口相关;

/**
 * @author: xiaomi
 * @date: 2021/2/4
 * @description: 643. 子数组最大平均数 I
 * https://leetcode-cn.com/problems/maximum-average-subarray-i/
 */
public class A_643_子数组最大平均数_I {

    public static void main(String[] args) {
        int[] nums = new int[]{4, 2, 1, 3, 3};
        int k = 2;
        A_643_子数组最大平均数_I action = new A_643_子数组最大平均数_I();
        double res = action.findMaxAverage(nums, k);
        System.out.println("res = " + res);

    }

    /**
     * 肯定得遍历一遍
     * 由于数据范围所以不存在越界的情况
     * --
     * 1.计算总数最大的值
     *
     * @param nums
     * @param k
     * @return
     */
    public double findMaxAverage(int[] nums, int k) {
        int len = nums.length;
        //初始化 平均数
        int sum = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }
        //[)
        int begin = 0, end = k;
        int res = sum;
        while (end < len) {
            sum = sum - nums[begin++] + nums[end++];
            res = Math.max(res, sum);
        }
        return (double) res / k;
    }


}
